#include "web.h"
#include "../config/config.h"
#include <ESP8266WebServer.h>
#include <FS.h>

Web::Web()
{
    WebController = new ESP8266WebServer(WebServerPort);
}

void Web::init()
{
    // 启动闪存文件系统
    if (SPIFFS.begin()) { 
        Serial.println("SPIFFS Started.");
    } else {
        Serial.println("SPIFFS Failed to Start.");
    }

    WebController->onNotFound(
        std::bind(&Web::handleUserRequest, this)
    );
    WebController->begin();
    Serial.println("HTTP server started");
}

void Web::handleUserRequest()
{
    String reqResource = WebController->uri();
    Serial.print("reqResource: ");
    Serial.println(reqResource);
    bool fileReadOK = handleFileRead(reqResource);
    if (!fileReadOK)
    {
        WebController->send(404, "text/plain", "404 Not Found");
    }
}

bool Web::handleFileRead(String resource)
{
    if (resource.endsWith("/"))
    {                             // 如果访问地址以"/"为结尾
        resource = "/index.html"; // 则将访问地址修改为/index.html便于SPIFFS访问
    }
    String contentType = getContentType(resource); // 获取文件类型

    if (SPIFFS.exists(resource))
    { // 如果访问的文件可以在SPIFFS中找到
        Serial.println("have file.....");
        File file = SPIFFS.open(resource, "r");       // 则尝试打开该文件
        WebController->streamFile(file, contentType); // 并且将该文件返回给浏览器
        file.close();                                 // 并且关闭文件
        return true;                                  // 返回true
    }
    return false; // 如果文件未找到，则返回false
}

String Web::getContentType(String filename)
{
    if (filename.endsWith(".htm"))
        return "text/html";
    else if (filename.endsWith(".html"))
        return "text/html";
    else if (filename.endsWith(".css"))
        return "text/css";
    else if (filename.endsWith(".js"))
        return "application/javascript";
    else if (filename.endsWith(".png"))
        return "image/png";
    else if (filename.endsWith(".gif"))
        return "image/gif";
    else if (filename.endsWith(".jpg"))
        return "image/jpeg";
    else if (filename.endsWith(".ico"))
        return "image/x-icon";
    else if (filename.endsWith(".xml"))
        return "text/xml";
    else if (filename.endsWith(".pdf"))
        return "application/x-pdf";
    else if (filename.endsWith(".zip"))
        return "application/x-zip";
    else if (filename.endsWith(".gz"))
        return "application/x-gzip";
    return "text/plain";
}